Complete sample code to send an email:
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Default {
public static String apiKey = "ApiKey";
public static void main(String[] args) throws Exception {
try {
sendEmail();
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
private static void sendEmail() throws Exception {
String url = "https://messagingapis.paylite.net/api/email/send";
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
JsonObject fromEmail = new JsonObject();
fromEmail.addProperty("Email", "From Email");
fromEmail.addProperty("Name", "From Name");
JsonArray toEmails = new JsonArray();
JsonObject toEmail = new JsonObject();
toEmail.addProperty("Email", "To Email");
toEmail.addProperty("Name", "To Name");
toEmails.add(toEmail);
JsonObject jsonData = new JsonObject();
jsonData.addProperty("ApiKey", apiKey);
jsonData.add("FromEmail", fromEmail);
jsonData.add("ToEmail", toEmails);
jsonData.addProperty("Subject", "Paylite Messaging");
jsonData.addProperty("HtmlContent", "PayLite test content");
String postJsonData = gson.toJson(jsonData);
System.out.println(postJsonData);
postRequest(url, postJsonData);
}
private static void postRequest(String url, String postJsonData) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Setting basic post request
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postJsonData);
wr.flush();
wr.close();
//Read output
BufferedReader in =new BufferedReader(new InputStreamReader(con.getInputStream()));
String output;
StringBuffer response = new StringBuffer();
while ((output = in.readLine()) != null) {
response.append(output);
} in .close();
// printing result from response
System.out.println(response.toString());
}
}